package job.work.service.system.service.impl;

import com.alibaba.druid.util.StringUtils;
import job.work.dao.system.dao.DecMenuDao;
import job.work.dao.system.dao.DecRoleMenuDao;
import job.work.domain.response.CommonCode;
import job.work.domain.response.ResponseResult;
import job.work.domain.system.entity.pojo.DecMenu;
import job.work.domain.system.entity.pojo.DecRole;
import job.work.domain.system.entity.pojo.DecRoleMenu;
import job.work.mapper.system.RoleMapper;
import job.work.mapper.system.SystemMapper;
import job.work.service.system.service.DecRolesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author zzy
 * @Classname DecRoles
 * @Date 2020/9/25 15:46
 * @Created by Administrator
 */

@Service
public class DecRolesServiceImpl implements DecRolesService {

    /**
     * 角色接口
     */
    @Resource
    RoleMapper roleMapper;

    /**
     * 角色菜单中间表接口
     */
    @Resource
    DecRoleMenuDao decRoleMenuDao;

    @Resource
    SystemMapper systemMapper;

    @Resource
    DecMenuDao decMenuDao;

    @Resource
    DecMenuServiceImpl decMenuServiceImpl;



    /**
     * 后台管理查询所有角色
     *
     * @return 操作结果
     */
    @Override
    public ResponseResult findAllRole() {

        List<DecRoleMenu> all1 = decRoleMenuDao.findAll();

        Map<Long, List<Long>> maps = new HashMap<>();

        for (DecRoleMenu decRoleMenu : all1) {
            List<Long> list = maps.get(decRoleMenu.getRoleId());
            if (list == null || list.size() < 1) {
                list = new ArrayList<>();
            }

            list.add(decRoleMenu.getMenuId());

            maps.put(decRoleMenu.getRoleId(), list);
        }
        List<DecRole> decRoles = roleMapper.findByStatus(0);
        decRoles.forEach(decRole -> decRole.setChildren(maps.get(decRole.getId())));

        return new ResponseResult<>(CommonCode.SUCCESS, decRoles);
    }

    /**
     * 修改/添加 角色
     *
     * @param decRole 角色对象
     * @return 操作结果
     */
    @Transactional
    @Override
    public ResponseResult saveRole(DecRole decRole) {
        //判读角色名是否重复
        DecRole byName = roleMapper.findByName(decRole.getName());
        if (byName != null) {
            if (decRole.getId() == null || !decRole.getId().equals(byName.getId())) {
                return new ResponseResult<>(CommonCode.FAIL, "角色名称重复!");
            }
        }
        try {
            if (decRole.getId() != null) {
                //修改
                Optional<DecRole> byId = roleMapper.findByRoleId(decRole.getId());
                if (!byId.isPresent()) {
                    return new ResponseResult<>(CommonCode.INVALID_PARAM);
                }
                roleMapper.updateByPrimaryKey(decRole);
                decRoleMenuDao.deleteAllByRoleId(byId.get().getId());
            } else {
                roleMapper.insertSelective(decRole);
            }
            //保存角色权限集合
            List<DecRoleMenu> decRoleMenus = new ArrayList<>();
            for (Long permission : decRole.getChildren()) {
                DecRoleMenu decRoleMenu = new DecRoleMenu();
                decRoleMenu.setMenuId(permission);
                decRoleMenu.setRoleId(decRole.getId());
                decRoleMenus.add(decRoleMenu);
            }
            //保存角色权限
            decRoleMenuDao.saveAll(decRoleMenus);
            return ResponseResult.SUCCESS();
        } catch (Exception e) {
            return new ResponseResult<>(CommonCode.SERVER_ERROR);
        }
    }

    /**
     * 根据角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 操作结果
     */
    @Transactional
    @Override
    public ResponseResult deleteRole(Long roleId) {
        int cont = systemMapper.findByRoleIdCont(roleId);
        if (cont > 0) {
            return new ResponseResult<>(CommonCode.FAIL, "该角色下面有用户,无法删除");
        }
        if (roleId<=5){
            return new ResponseResult<>(CommonCode.FAIL, "默认角色,无法删除!");
        }
        List<DecRoleMenu> byRoleId = decRoleMenuDao.findByRoleId(roleId);

        decRoleMenuDao.deleteAll(byRoleId);
        Optional<DecRole> byId = roleMapper.findByRoleId(roleId);
        if (byId.isPresent()) {
            roleMapper.delete(byId.get());
            return ResponseResult.SUCCESS();
        } else {
            return new ResponseResult<>(CommonCode.INVALID_PARAM);
        }
    }



    /**
     * 根据角色id查询当前角色有哪些权限 只要最后一级
     * */
    @Override
    public ResponseResult findLastRole(Long roleId){
        //查询中间表
        List<DecRoleMenu> byRoleId = decRoleMenuDao.findByRoleId(roleId);

        Set<Long> set = new HashSet<>();

        //根据角色返权限
        for(DecRoleMenu br:byRoleId){
            set.add(br.getMenuId());
        }

        List<DecMenu> byIdIn = decMenuDao.findByIdIn(set);

        //decMenuService.getRootTree(roleId,);

        Set<Long> sets = aroundId(byIdIn);

        return new ResponseResult(CommonCode.SUCCESS,sets);
    }


    /**
     * 根据角色返回角色所有的权限
     * */
    @Override
    public ResponseResult findByEachRole(Long roleId){
        if(Objects.equals(roleId,null)){
            return new ResponseResult(CommonCode.FAIL);
        }
        //中间表
        Set<Long> byMenu = decRoleMenuDao.findByMenu(roleId);

        //权限表
        List<DecMenu> menu = decMenuDao.findByIdIn(byMenu);
        List<DecMenu> menuTree = decMenuServiceImpl.getMenuTree(menu);

        return new ResponseResult(CommonCode.SUCCESS,menuTree);
    }




    private Set<Long> aroundId(List<DecMenu> decMenus){

        Set<Long> set = new HashSet<>();

        for(DecMenu de:decMenus){
            if(!de.getPid().equals(0L) && !StringUtils.isEmpty(de.getUrl())){
                set.add(de.getId());
            }
        }
        return set;
    }


}
